import config from "@/config/config";
import $global from "./$global";

//深拷贝
function deepCopy(data) {
  if (data && typeof data === "object") {
    //针对函数的拷贝
    if (typeof data === "function") {
      let tempFunc = data.bind(null);
      tempFunc.prototype = deepCopy(data.prototype);
      return tempFunc;
    }

    switch (Object.prototype.toString.call(data)) {
      case "[object String]":
        return data.toString();
      case "[object Number]":
        return Number(data.toString());
      case "[object Boolean]":
        return new Boolean(data.toString());
      case "[object Date]":
        return new Date(data.getTime());
      case "[object Array]":
        var arr = [];
        for (let i = 0; i < data.length; i++) {
          arr[i] = deepCopy(data[i]);
        }
        return arr;

      //js自带对象或用户自定义类实例
      case "[object Object]":
        var obj = {};
        for (let key in data) {
          //会遍历原型链上的属性方法，可以用hasOwnProperty来控制 （obj.hasOwnProperty(prop)
          obj[key] = deepCopy(data[key]);
        }
        return obj;
    }
  } else {
    //string,number,bool,null,undefined,symbol
    return data;
  }
}

/**
 *
 * @param key  缓存名称
 * @param val  缓存数据
 */
function setlocalStorage(key, val, prefix = "") {
  let data = val;
  if (val && typeof val == "object") {
    data = JSON.stringify(val);
  }

  localStorage.setItem((prefix || config.prefix) + key, data);
}
/**
 * 获取本地缓存
 * @param key  缓存名称
 */
function getlocalStorage(key, prefix = "") {
  let item = localStorage.getItem((prefix || config.prefix) + key);
  return item;
}
/**
 * 移除本地缓存
 * @param key  缓存名称
 */
function removelocalStorage(key, prefix = "") {
  localStorage.removeItem((prefix || config.prefix) + key);
}

/**
 * 检测本地缓存
 * @param key   缓存名称
 * @returns {boolean|any}
 */
function checklocalStorage(key, prefix) {
  let data = getlocalStorage(key, prefix);
  if (data) {
    let checkData = isJSON(data);
    if (checkData) {
      return checkData;
    } else {
      return data;
    }
  } else {
    return false;
  }
}

//检测是否为JSON
function isJSON(str) {
  if (typeof str == "string") {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == "object" && obj) {
        return obj;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  } else {
    return false;
  }
}

//获取自定义时间格式
function getCustomTime(time, type = "YYYY-MM-DD hh:mm:ss") {
  let date = "";

  if (time) {
    if (typeof time == "string") {
      time = time.replace(/\-/g, "/");
      time = time.replace(/\./g, "/");
    }

    date = new Date(time);
  } else {
    date = new Date();
  }
  //返回时间戳

  if (type == "timestamp") {
    return date.getTime();
  }

  let YYYY = date.getFullYear();

  //月
  let M = date.getMonth() + 1;
  let MM = M.toString().padStart(2, "0");

  //日
  let D = date.getDate();
  let DD = D.toString().padStart(2, "0");

  //时
  let h = date.getHours();
  let hh = h.toString().padStart(2, "0");

  //分
  let m = date.getMinutes();
  let mm = m.toString().padStart(2, "0");

  //秒
  let s = date.getSeconds();
  let ss = s.toString().padStart(2, "0");

  type = type.replace(/YYYY/g, YYYY);

  type = type.replace(/MM/g, MM);
  type = type.replace(/M/g, M);

  type = type.replace(/DD/g, DD);
  type = type.replace(/D/g, D);

  type = type.replace(/hh/g, hh);
  type = type.replace(/h/g, h);

  type = type.replace(/mm/g, mm);
  type = type.replace(/m/g, m);

  type = type.replace(/ss/g, ss);
  type = type.replace(/s/g, s);
  return type;
}

//获取前day至当前时间
function getOverTime(days) {
  if (!days) {
    console.log("请传入时间");
    return;
  }
  let currentTime = Date.now();
  let day = 1000 * 60 * 60 * 24;
  let overTime = currentTime - day * days;
  return getCustomTime(overTime);
}

//复制文本
function copyMsg(val, tip) {
  const inputCtx = document.createElement("input");
  inputCtx.value = val;
  inputCtx.style.position = "absolute";
  inputCtx.style["z-index"] = "-100";
  document.body.appendChild(inputCtx);
  inputCtx.select();
  document.execCommand("copy");
  $global.openN(tip || "复制成功");
  inputCtx.remove();
}

//读取本地图片
function require(url) {
  return new URL(url, import.meta.url).href;
}

//将图片转为dom
function loadImage(url) {
  return new Promise((resolve, reject) => {
    try {
      const img = new Image();
      img.crossOrigin = "Anonymous";
      img.src = url;
      img.onload = (data) => {
        if (data.type == "load") {
          resolve(img);
        } else {
          reject(false);
        }
      };
      img.onerror = () => {
        reject(false);
      };
    } catch {
      reject(false);
    }
  });
}

//将图片的dom节点转为base64数据
function imageDomToBase64(imageDom) {
  let arr = imageDom.src.split(".");
  let prefix = arr[arr.length - 1];
  let legalList = ["png", "jpg", "jpeg", "svg"];
  if (!legalList.includes(prefix)) {
    console.log("不正确的图片格式");
    return "";
  }

  const canvas = document.createElement("canvas");
  canvas.width = imageDom.width;
  canvas.height = imageDom.height;
  const ctx = canvas.getContext("2d");
  ctx.drawImage(imageDom, 0, 0);
  return canvas.toDataURL(`image/${prefix}`);
}

export default {
  deepCopy,
  setlocalStorage,
  getlocalStorage,
  removelocalStorage,
  checklocalStorage,
  isJSON,
  getCustomTime,
  copyMsg,
  getOverTime,
  require,
  loadImage,
  imageDomToBase64,
};
